package logic

import (
	"bytes"
	"context"
	"encoding/json"
	"log"
	"srv/model/es"

	"srv/internal/svc"
	"srv/renrenzu"

	"github.com/zeromicro/go-zero/core/logx"
)

type SyncGoodsEsOneLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSyncGoodsEsOneLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SyncGoodsEsOneLogic {
	return &SyncGoodsEsOneLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SyncGoodsEsOneLogic) SyncGoodsEsOne(in *renrenzu.SyncGoodsEsOneRequest) (*renrenzu.GoodsListOneResponse, error) {
	// todo: add your logic here and delete this line
	var buf bytes.Buffer
	var query = map[string]interface{}{}
	if in.KeyName == "" {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match_all": map[string]interface{}{},
			},
		}

	} else {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match": map[string]interface{}{
					"GoodsTitle": in.KeyName,
				},
			}}
	}
	if err := json.NewEncoder(&buf).Encode(query); err != nil {
		log.Fatalf("Error encoding query: %s", err)
	}
	res, err := es.Es.Search(
		es.Es.Search.WithContext(context.Background()),
		es.Es.Search.WithIndex("goods"),
		es.Es.Search.WithBody(&buf),
		es.Es.Search.WithTrackTotalHits(true),
		es.Es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()

	if res.IsError() {
		var e map[string]interface{}
		if err := json.NewDecoder(res.Body).Decode(&e); err != nil {
			log.Fatalf("Error parsing the response body: %s", err)
		} else {
			// Print the response status and error information.
			log.Fatalf("[%s] %s: %s",
				res.Status(),
				e["error"].(map[string]interface{})["type"],
				e["error"].(map[string]interface{})["reason"],
			)
		}
	}
	r := map[string]interface{}{}
	if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
		log.Fatalf("Error parsing the response body: %s", err)
	}
	// Print the response status, number of results, and request duration.
	log.Printf(
		"[%s] %d hits; took: %dms",
		res.Status(),
		int(r["hits"].(map[string]interface{})["total"].(map[string]interface{})["value"].(float64)),
		int(r["took"].(float64)),
	)
	// Print the ID and document source for each hit.
	list := []*renrenzu.GoodsList{}
	for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
		log.Printf(" * ID=%s, %s", hit.(map[string]interface{})["_id"], hit.(map[string]interface{})["_source"])
		seath := hit.(map[string]interface{})["_source"].(map[string]interface{})
		list = append(list, &renrenzu.GoodsList{
			GoodsTitle:      seath["GoodsTitle"].(string),
			GoodsCover:      seath["GoodsCover"].(string),
			GoodsPrice:      float32(seath["GoodsPrice"].(float64)),
			GoodsStock:      int64(seath["GoodsStock"].(float64)),
			GoodsCollection: int64(seath["GoodsCollection"].(float64)),
			GoodsState:      int64(seath["GoodsState"].(float64)),
		})
	}

	return &renrenzu.GoodsListOneResponse{List: list}, nil
}
